var app = sm("do_App");
var page = sm("do_Page");
var rootview = ui("$");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var mallUrl = require("url/mall");
var userUrl = require("url/user");
var couponUrl = require("url/coupon");
var qqHttp = require("helper/http");
var orderHelper = require("helper/order");
var httpSilence = require("helper/httpSilence");
var qqmath = require("util/qqmath");
var communityUtil = require("helper/community");

var do_LinearLayout_item = ui("do_LinearLayout_item");
var do_Button_order = ui("do_Button_order");
var do_ALayout_address = ui("do_ALayout_address");
var do_Label_address = ui("do_Label_address");
var do_TextField_remark = ui("do_TextField_remark");
var do_Label_delivery = ui("do_Label_12");
var deliveryAout = ui("deliveryAout");
var helperOpen = require("helper/open");
var listview = ui("do_ListView");
var listdata = mm("do_ListData");
var nf = sm("do_Notification");
listview.bindItems(listdata);
var noData = [{"template":1}];

var param = {};
var selectItems = [];
var selectId;
var totalPriceLabel = ui("totalPriceLabel");
//促销
var requirement = 0;
var subsidy = 0;
var salesName="";
//起送金额
var freeDeliverValue = 0.00;
//配送方式：1-自提；2-店铺配送；3-圈圈配送
var deliveryType = 2;
//起送金额提示信息
var deliveryMsg = "";
//andriod返回键
var isDraw=false;
page.on("back", function() {
    app.closePage({"cart_toOrder":true});
});

page.on("result", function(data) {
	if (data) {
		if (data.nextAddr || data.houseNumber) {
			do_Label_address.text = data.contactName + " " + data.address;
			param.addressId = data.id;
			selectId = data.id;
		}
	}
});

/* 头部 */
var headerAout = ui("do_ALayout_header");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
var header = ui("header");
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
var labelTitle = ui(addheader+".labelTitle");
labelTitle.text = "提交订单";
headerLeft.on("touch", function() {
    app.closePage({"cart_toOrder":true})
});

page.on("loaded", function(){
	//读取当前页面的传入参数
	var data = page.getData();
	param.visitCommunityId = communityUtil.communityVisitId();//当前访问
	init(data);
});

var totalPrice;
var couponUserIds;
var totalMinu=0.00;
var isOutsideCouponUser=false;
var isInsideCouponUser=false;
function init(data) {
	//读取当前页面传入的参数 
	selectItems = data.addItems;
	totalPrice = qqmath.getDight(data.total,2);
    //获取默认地址
	qqHttp.post(userUrl.url.address.getDefault, {}, function(data) {
		if (data && data.userAddress) {
			var userAddress = data.userAddress;
			do_Label_address.text = userAddress.contactName + " " + userAddress.address;
			param.addressId = userAddress.id;
			selectId = userAddress.id;
		}
	});
	//是否抽奖产品
	if(null!=data.fromPage&&data.fromPage=="draw_index"){
		isDraw=true;
	}else{
		isDraw=false;
	}
	//获取商城配送、促销活动参数
	httpSilence.post(mallUrl.url.order.getDisParam, {}, function(data) {
		if(data && data.freeDeliverValue){
			freeDeliverValue = data.freeDeliverValue;
			if(deliveryType == 2){
				if(selectItems[0].supplierType == 1){
					do_Label_delivery.text="商家配送";
					do_Label_delivery.visible = true;
					deliveryAout.visible=false;
				}
				checkFreeDeliver(freeDeliverValue,isDraw);//校验各商家交易金额是否满足起送金额
			}
		}
		//促销-满减活动
		if(data && data.sales){
			requirement = data.sales.requirement;
			subsidy = data.sales.subsidy;
			salesName = data.sales.name;
			if(totalPrice >= requirement){
				var temp = qqmath.getDight(totalPrice-subsidy,2);
				if(temp >= 0){
					totalPriceLabel.text = temp+'';
					ui("do_Label_9").text="("+salesName+")";
				}else{
					nf.toast("活动信息错误");
					totalPriceLabel.text = totalPrice+'';
				}
			}else{
				totalPriceLabel.text = totalPrice+'';
			}
		}else{
			totalPriceLabel.text =totalPrice+'';
		}
		//优惠券
		myCouponList();
	});
	if(selectItems.length){
		listdata.addData(selectItems);
	}else{
		listdata.addData(noData);
	}
	listview.refreshItems();
}

function myCouponList(){
	var orderItems=page.getData().addItems;
	var couponUserId=page.getData().couponUserId;
	for (var i=0; i<orderItems.length; i++) {
		orderItems[i].quntity = orderItems[i].quantity;
		orderItems[i].productId = orderItems[i].onlyProductId;
		orderItems[i].supplierType=orderItems[i].supplierType;
	}
	var params = {
		orderItems:orderItems,
		id:couponUserId
	};
	httpSilence.post(couponUrl.url.user.mallCoupon, params, function(data) {
		for (var i = 0; i < data.myCoupon.length; i++) {
			data.myCoupon[i].template=2;
		}
		couponUserIds=data.couponUserIds;
		totalMinu=data.totalMinu;
		param.orderCouponList=data.orderCouponList;
		param.totalMinu=totalMinu;
		totalPriceLabel.text =qqmath.getDight(totalPriceLabel.text-totalMinu,2)+'';
		listdata.addData(data.myCoupon);
		listview.refreshItems();
	});
}

function checkFreeDeliver(freeDeliverValue,isDraw){
	//判断是否满足起送金额
	var selectItems = page.getData().addItems;
	for(var i=0; i < selectItems.length; i++){
		var supplierId = selectItems[i].supplierId;
		var supplierType = selectItems[i].supplierType;
		var externalSupplierPrice = 0.00;

		for(var j=0; j < selectItems.length; j++){
			if(selectItems[j].supplierType == supplierType && supplierType == 1){//圈圈直供
				externalSupplierPrice = externalSupplierPrice + parseFloat(selectItems[j].price) * parseInt(selectItems[j].quantity);
			}
		}
		if(!isDraw&&(supplierType == 1 && externalSupplierPrice < freeDeliverValue)){
			do_Button_order.bgColor = "949EAAFF";
			deliveryMsg = "商品满"+freeDeliverValue+"元起送";
			break;
		}
	}
}

//选择地址
do_ALayout_address.on("touch", function() {
	helperOpen.open("source://view/user/userAddress/list.ui",{select:true,selectId:selectId});
});

do_Button_order.on("touch", '',1000,function(data, e){
	if(deliveryMsg != ""){
		nf.toast(deliveryMsg);
		return;
	}
	var orderItems = [];
	for (var i=0; i<selectItems.length; i++) {
		var orderItem = {"productId":"","quntity":"","supplierId":""};
		orderItem.productId = selectItems[i].productId;
		orderItem.quntity = selectItems[i].quantity;
		orderItem.supplierId = selectItems[i].supplierId;
		orderItems.push(orderItem);
	}
	param.orderItems = orderItems;
	param.remark = do_TextField_remark.text;
	param.deliveryType = deliveryType;
	param.orderType = orderHelper.type.QUANMALL;
	param.shopId = 1;//店铺ID
	if(deliveryType == 2){
		if(!selectId){
			nf.toast("请选择收货地址");
			return;
		}
		qqHttp.post(mallUrl.url.order.doAdd, param, function(data) {
			nf.toast("下单成功");
			if(data.zeroFlag && data.zeroFlag !== "undefined" && data.zeroFlag == "1"){
				helperOpen.openBuyerOrder(data.orderNo);
			}else{
				orderHelper.toPay(data.orderNo);
			}
		});
	}
});

function fD(a, b, c) {
	for (; a > c;)
		a -= c - b;
	for (; a < b;)
		a += c - b;
	return a;
};
function jD(a, b, c) {
	b != null && (a = Math.max(a, b));
	c != null && (a = Math.min(a, c));
	return a;
};
function yk(a) {
	return Math.PI * a / 180
};
function Ce(a, b, c, d) {
	var dO = 6370996.81;
	return dO * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a));
};
function getDistance(a, b) {
	if (!a || !b)
		return 0;
	a.lng = fD(a.lng, -180, 180);
	a.lat = jD(a.lat, -74, 74);
	b.lng = fD(b.lng, -180, 180);
	b.lat = jD(b.lat, -74, 74);
	return Ce(yk(a.lng), yk(b.lng), yk(a.lat), yk(b.lat));
};